const passport = require("koa-passport");
const LocalStrategy = require("passport-local").Strategy;
const User = require("../../dbs/models/user");

// 注册本地验证策略
passport.use(
  new LocalStrategy(async (username, password, done) => {
    if (!(username && passport)) {
      return done(null, false, "信息错误");
    }
    // 作用于登录
    let user = await User.findOne({ username });
    if (user) {
      if (!require("bcryptjs").compareSync(password, user.password)) {
        return done(null, false, "密码错误");
      }
      return done(null, user, "登录成功");
    }
    return done(null, false, "用户不存在");
  })
);

// 序列化
passport.serializeUser((user, done) => {
  let { id } = user;
  done(null, id);
});

// 反序列化
passport.deserializeUser((id, done) => {
  console.log(id, "我是反序列化");
  done(null, "我来自反序列化");
});

module.exports = passport;
